#include "mongoc_const.h"

module mongof_common_mod

  use flogger

  implicit none

  interface
    subroutine mongoc_init() bind(c, name='mongoc_init')
    end subroutine mongoc_init

    integer function mongoc_connect(uri, db_name, col_name, cid) result(ierr) bind(c, name='mongoc_connect')
      use iso_c_binding
      character(c_char), intent(in) :: uri(*)
      character(c_char), intent(in) :: db_name(*)
      character(c_char), intent(in) :: col_name(*)
      integer(c_int), intent(out) :: cid
    end function mongoc_connect

    integer function mongoc_create_index(cid, index_name) result(ierr) bind(c, name='mongoc_create_index')
      use iso_c_binding
      integer(c_int), intent(in) :: cid
      character(c_char), intent(in) :: index_name(*)
    end function mongoc_create_index

    integer function mongoc_create_platform_index(cid) result(ierr) bind(c, name='mongoc_create_platform_index')
      use iso_c_binding
      integer(c_int), intent(in) :: cid
    end function mongoc_create_platform_index

    integer function mongoc_create_record_index(cid) result(ierr) bind(c, name='mongoc_create_record_index')
      use iso_c_binding
      integer(c_int), intent(in) :: cid
    end function mongoc_create_record_index

    integer function mongoc_create_drift_record_index(cid) result(ierr) bind(c, name='mongoc_create_drift_record_index')
      use iso_c_binding
      integer(c_int), intent(in) :: cid
    end function mongoc_create_drift_record_index

    subroutine mongoc_final() bind(c, name='mongoc_final')
    end subroutine mongoc_final
  end interface
 
contains

  subroutine handle_mongo_error(ierr, file, line)

    integer, intent(in) :: ierr
    character(*), intent(in) :: file
    integer, intent(in) :: line

    if (ierr >= 0) return

    select case (ierr)
    case (FORTRAN_MONGO_MEMORY_ERROR)
      call log_error('Encounter mongo memory error!', file, line)
    case (FORTRAN_MONGO_URI_NEW_ERROR)
      call log_error('Failed to create mongo uri object!', file, line)
    case (FORTRAN_MONGO_CLIENT_NEW_ERROR)
      call log_error('Failed to create mongo client object!', file, line)
    case (FORTRAN_MONGO_BAD_DB_ID)
      call log_error('Invalid mongo database name!', file, line)
    case (FORTRAN_MONGO_BAD_QUERY)
      call log_error('Invalid mongo query!', file, line)
    case (FORTRAN_MONGO_BAD_CURSOR)
      call log_error('Invalid mongo cursor!', file, line)
    case (FORTRAN_MONGO_BSON_NEW_ERROR)
      call log_error('Failed to create bson object!', file, line)
    case (FORTRAN_MONGO_INSERT_ERROR)
      call log_error('Failed to insert document!', file, line)
    case default
      call log_error('Unknown mongo error!', file, line)
    end select

  end subroutine handle_mongo_error

end module mongof_common_mod
